import React, {useEffect, useState} from 'react';
import {ModalForm} from "@ant-design/pro-form";
import {ProColumns, ProTable} from "@ant-design/pro-table";
import {LendLogItem} from "@/pages/LendLogs/data";
import {message, Popconfirm} from "antd";
import {DeleteOutlined} from "@ant-design/icons";
import {deleteLendPaybackLog, queryLendPayBackLog} from "@/pages/LendLogs/service";

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<LendLogItem>;

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  modalVisible: boolean;
  values: Partial<LendLogItem>;
};

/**
 * 删除节点
 *
 * @param record
 * @param lendLog
 */
const handleSingleRemove = async (record: any, lendLog: LendLogItem) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteLendPaybackLog({
      lendId: lendLog.id,
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const PaybackLogForm: React.FC<UpdateFormProps> = (props) => {

  // 设置表格源
  const [data, setData] = useState<any[]>([])
  const [update, setUpdate] = useState(false)

  useEffect(() => {
    if (props.values.id !== undefined){
      queryLendPayBackLog({lendId: props.values?.id}).then(r => {
        if (r.status === "done"){
          setData(r.data)
        }
      })
    }
  }, [props.values, update]);

  const columns: ProColumns<any>[] = [
    {
      title: "id",
      dataIndex: "id",
      hideInTable: true
    },
    {
      title: "还钱时间",
      dataIndex: "time",
      valueType: "dateTime"
    },
    {
      title: "金额",
      dataIndex: "money",
      valueType: "money"
    },
    {
      title: "备注",
      dataIndex: "remark",
      valueType: "text"
    },
    {
      title: "",
      valueType: "option",
      align: "right",
      width: 30,
      render: (_, record)=>[
         <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={async () => {
            const success = await handleSingleRemove(record, props.values as LendLogItem);
            if (success) {

              // 删除成功，重新获取数据
              if (update){
                setUpdate(false)
              }else {
                setUpdate(true)
              }
            }
          }}>
            <a style={{color: "gray"}} ><DeleteOutlined /></a>
        </Popconfirm>
      ]
    },
  ];

  return (
    <ModalForm
      title={"明细"}
      visible={props.modalVisible}
      // width={0}
      // Drawer抽屉需要关联上层UpdateForm的点击管理函数
      onFinish={props.onSubmit}
      modalProps={{
        destroyOnClose: true,
        // 抽屉层关闭函数， 需要关联上层的onCancel函数
        onCancel: function (){
          props.onCancel()
        },
      }}
      submitter={{
          resetButtonProps: {
            style: {
              display: 'none',
            },
          },
          submitButtonProps: {
            style: {
              display: 'none',
            },
          },
      }}
    >
      <ProTable
        defaultSize={"small"}
        pagination={false}
        search={false}
        toolBarRender={false}
        columns={columns}
        dataSource={data}
      />
    </ModalForm>
  );
};

export default PaybackLogForm;
